package core.message;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AliSmsService {
    private static final Logger logger = LoggerFactory.getLogger(AliSmsService.class);

    @Value(value = "${sms.sign-name}")
    private String signName;

    @Value(value = "${sms.template-code}")
    private String templateCode;

    @Autowired
    private Client client;

    public boolean sendMobileCode(String phone, String code) {
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        return sendMessage(phone, signName, templateCode, map);
    }
    /**
     * 发送短信
     *
     * @param templateCode 模板号
     * @param phone 手机号
     * @param param 模板参数 {"key":"value"}
     */
    public boolean sendMessage(String phone, String signName, String templateCode, Map<String, String> param) {
        try {
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setPhoneNumbers(phone)
                    .setTemplateParam(JSON.toJSONString(param));
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            if (null != response.getBody()
                    && null != response.getBody().getMessage()
                    && "OK".equals(response.getBody().getMessage())) {
                logger.info("向{}发送信息成功，templateCode={}", phone, templateCode);
                return true;
            } else {
                logger.error("向{}发送信息失败，templateCode={}，失败原因：{}",
                    phone, templateCode, response.getBody().getMessage());
                return false;
            }
        } catch (TeaException error) {
            logger.error("向{}发送信息失败，templateCode={}", phone, templateCode, error);
            return false;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            logger.error("向{}发送信息失败，templateCode={}", phone, templateCode, error);
            return false;
        }
    }
}
